package au.com.georgi.wave.parser;

import java.util.logging.Logger;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;

import au.com.georgi.wave.entity.ArmoryCharacter;

public class ArmoryParser implements Parser {

	private static final Logger log = Logger.getLogger(ArmoryParser.class
			.getName());
	private final Document doc;

	public ArmoryParser(Document doc) {
		this.doc = doc;
	}

	public ArmoryCharacter parseSource() {
		log.warning("Beginning parse of source... ");

		ArmoryCharacter armoryCharacter = new ArmoryCharacter();
		XPathFactory factory = XPathFactory.newInstance();
		XPath xpath = factory.newXPath();

		try {
			XPathExpression expr = xpath.compile("//characterInfo/character");

			Object result = expr.evaluate(doc, XPathConstants.NODESET);
			NodeList nodes = (NodeList) result;
			for (int i = 0; i < nodes.getLength(); i++) {
				NamedNodeMap attributes = nodes.item(i).getAttributes();
				armoryCharacter.setName(attributes.getNamedItem("name")
						.getNodeValue());
				armoryCharacter.setCharClass(attributes.getNamedItem("class")
						.getNodeValue());
				armoryCharacter.setFaction(attributes.getNamedItem("faction")
						.getNodeValue());
				armoryCharacter.setGuildName(attributes.getNamedItem(
						"guildName").getNodeValue());
				armoryCharacter.setRace(attributes.getNamedItem("race")
						.getNodeValue());
				armoryCharacter.setRealm(attributes.getNamedItem("realm")
						.getNodeValue());
				armoryCharacter.setLevel(attributes.getNamedItem("level")
						.getNodeValue());
				log.warning("Armory Character created: "
						+ armoryCharacter.toString());
			}
		} catch (XPathExpressionException e) {
			log.severe("Failed to parse source" + e.getMessage());
		}

		log.warning("Finished parsing of source... "
				+ armoryCharacter.toString());
		return armoryCharacter;
	}
}
